package com.hy.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.common.Result;
import com.hy.entity.Weekly;
import com.hy.entity.WeeklyLike;
import com.hy.mapper.WeeklyLikeMapper;
import com.hy.mapper.WeeklyMapper;
import com.hy.service.WeeklyLikeService;
import com.hy.service.WeeklyService;
import com.hy.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class WeeklyServiceImpl extends ServiceImpl<WeeklyMapper, Weekly> implements WeeklyService {

    @Autowired
    private WeeklyLikeService weeklyLikeService;

    @Autowired
    private UserUtil userUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> likeWeekly(Weekly weekly) {

        // 判断id是否为空
        if(ObjectUtil.isEmpty(weekly.getId())){
            return Result.error("入参为空");
        }
        Integer userId = userUtil.getUserIdFromToken();
        LambdaQueryWrapper<WeeklyLike> likeQueryWrapper = new LambdaQueryWrapper<>();
        likeQueryWrapper.eq(WeeklyLike::getUserId,userId);
        likeQueryWrapper.eq(WeeklyLike::getWeeklyId,weekly.getId());
        WeeklyLike one = weeklyLikeService.getOne(likeQueryWrapper);
        if(ObjectUtil.isNotEmpty(one)){
            return Result.error("你已经点赞过");
        }

        // 点赞+1
        Weekly dbWeekly = getById(weekly.getId());
        if (dbWeekly != null) {
            long likeNum = dbWeekly.getLikeNumbers() == null ? 0L : dbWeekly.getLikeNumbers();
            dbWeekly.setLikeNumbers(likeNum + 1);
            dbWeekly.setUpdateTime(new Date());
            updateById(dbWeekly);
        }

        // 插入用户点赞表
        WeeklyLike weeklyLike = new WeeklyLike();
        weeklyLike.setUserId(userId);
        weeklyLike.setWeeklyId(weekly.getId());
        weeklyLike.setDeleteFlag(0);
        weeklyLike.setCreateTime(new Date());
        weeklyLike.setUpdateTime(new Date());
        weeklyLikeService.save(weeklyLike);

        return Result.success("点赞成功");
    }
}